<template>
    <transition name="fade">
        <div class="toast" v-show="visible">
            <img src="../../assets/img/toast/success.png" alt="" v-if="type ==='success'"/>
            <img src="../../assets/img/toast/fail.png" alt="" v-if="type === 'fail'"/>
            <img src="../../assets/img/toast/warning.png" alt="" v-if="type === 'warning'"/>
            {{ message }}
        </div>
    </transition>
</template>

<script>
export default {
  name: "toast",
  components: {},
  data() {
    return {
      message: '', // 消息文字
      duration: 3000, // 显示时长，毫秒
      closed: false, // 用来判断消息框是否关闭
      timer: null, // 计时器
      visible: false, // 是否显示
      type: ''
    }
  },
  methods: {
    // 销毁当前元素
    destroyElement() {
      this.$destroy();
      this.$el.parentNode.removeChild(this.$el);
    },

    startTimer() {
      this.timer = setTimeout(() => {
        if (!this.closed) {
          this.closed = true;
          clearTimeout(this.timer)
        }
      }, this.duration)
    }
  },
  mounted() {
    this.startTimer();
  },
  beforeDestroy() {
  },
  watch: {
    closed(newVal) {
      if (newVal) {
        this.visible = false;
        this.destroyElement();
      }
    }
  },
}
</script>

<style scoped lang="scss">
    .toast {
        position: fixed;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        min-width: 40px;
        font-size: 16px;
        text-align: center;
        padding: 10px;
        border-radius: 4px;
        background-color: rgba(0, 0, 0, 0.6);
        color: rgb(223, 219, 219);
        display: flex;
        align-items: center;
        justify-content: center;

        > img {
            width: 36px;
            height: 36px;
        }
    }
</style>
